package com.huan.quartz.controller;

import com.huan.quartz.common.R;
import com.huan.quartz.domain.QuartzJobCfg;
import com.huan.quartz.service.QuartzJobCfgService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * quartz job 配置 controller
 *
 * @author huan.fu
 * @date 2018/9/10 - 15:08
 */
@RestController
@RequestMapping("quartz/job/cfg")
@Api(tags = "quartz job 配置管理控制层")
public class QuartzJobCfgController {

	@Autowired
	private QuartzJobCfgService quartzJobCfgService;

	@PostMapping("dynamic/class")
	@ApiOperation("动态更新job执行的class文件")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "主键", required = true, dataType = "Long", paramType = "query")
	})
	public R<String> addOrUpdateQuartzJobCfgAndJob(@ApiParam(value = "quartz job class file", required = true) @RequestParam("file") MultipartFile multipartFile, Long id) throws IOException {
		quartzJobCfgService.updateQuartzExecuteClass(multipartFile.getBytes(), id);
		return R.success("ok");
	}


	@PostMapping("add")
	@ApiOperation("添加系统中的quartz job 配置")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "jobChineseName", value = "job的中文名字", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "jobName", value = "job的英文名字", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "jobClass", value = "job任务执行的类", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "cronExpression", value = "job的调度表达式", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "jobStatus", value = "job的状态0-禁用 1-启用", required = true, dataType = "long", paramType = "query")
	})
	public R<String> addJobCfg(QuartzJobCfg jobCfg) {
		quartzJobCfgService.addJob(jobCfg);
		return R.success("ok");
	}

	@PostMapping("update")
	@ApiOperation("更新系统中的quartz job 配置")
	public R<String> updateJobCfg(@RequestBody QuartzJobCfg jobCfg) {
		quartzJobCfgService.updateJob(jobCfg);
		return R.success("ok");
	}

	@PostMapping("delete/{id}")
	@ApiOperation("根据id删除系统中的quartz job 配置，并从系统中移除这个job")
	@ApiImplicitParam(name = "id", value = "任务主键", required = true, dataType = "long", paramType = "path")
	public R<String> deleteJobCfg(@PathVariable("id") Long id) {
		quartzJobCfgService.deleteJob(id);
		return R.success("ok");
	}

	@GetMapping("findAll")
	@ApiOperation("获取系统中所有的定时任务配置")
	public R<List<QuartzJobCfg>> findAll() {
		return R.success(quartzJobCfgService.findAll());
	}
}
